package org.oschina.api.user.mail.dao;

import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.user.mail.model.UserMailRecord;
import org.oschina.api.user.mail.vo.UserMailRecordVo;
import org.springframework.stereotype.Repository;

@Repository
public class UserMailRecordDAO extends BaseDAO {

	private String getRecordCache(Object user)
	{
		return getKey(Constants.CACHE_USER_MAIL_RECORD,user);
	}
	public void updateRecord(int user,int mail,boolean read)
	{
		getCacheHelper().hset(getRecordCache(user), mail, read, Constants.TIMEOUT_USER_MAIL_RECORD);
	}
	public boolean isRead(int user,int mail)
	{
		Boolean result=(Boolean) getCacheHelper().hget(getRecordCache(user), mail, Boolean.class);
		if(result==null)
			result=false;
		
		return result;
	}
	public void removeCache(int user)
	{
		getCacheHelper().del(getRecordCache(user));
	}
	
	/**
	 * 根据邮件删除
	 * @param mail
	 * @return
	 */
	public int deleteByMail(int user,int mail)
	{
		getCacheHelper().hdel(getRecordCache(user), mail);
		return (int) getQueryHelper().delete(new String[]{"mail=?"}, new Object[]{mail},UserMailRecordVo.class);
	}
	
	/**
	 * 创建
	 * @param userMailRecord
	 * @return
	 */
	public UserMailRecord create(UserMailRecord userMailRecord)
	{
		updateRecord(userMailRecord.getUser(),userMailRecord.getMail(),true);
		getQueryHelper().insert(new String[]{"id","user","mail","create_time"}, 
				new Object[]{userMailRecord.getId(),userMailRecord.getUser(),userMailRecord.getMail(),userMailRecord.getCreate_time()},UserMailRecordVo.class);
		return userMailRecord;
	}
}